package com.woniu.log;

import com.woniu.entity.EverEmp;
import com.woniu.entity.EverLog;
import com.woniu.mapper.EverLogMapper;
import com.woniu.service.IEverLogService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.sql.Date;
import java.sql.SQLException;

@Aspect
@Component
public class Aop {
    @Resource
    private IEverLogService logService;
    @Resource
    private EverLogMapper logMapper;
    /***
     * 定义controller切入点拦截规则，拦截SystemControllerLog注解的方法
     */
    @Pointcut("@annotation(com.woniu.log.AnnotationLog)")
    public void controllerAspect(){}

    /***
     * 拦截控制层的操作日志
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("controllerAspect()")
    public Object recordLog( ProceedingJoinPoint joinPoint) throws Throwable {

        // 获取方法签名
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        // 获取方法
        Method method = methodSignature.getMethod();
        //获取方法的注解
        AnnotationLog annotationLog=method.getAnnotation(AnnotationLog.class);
        //获取方法上声明的操作
        String operateType = annotationLog.descrption();
        EverLog systemLog = new EverLog();
        //获取来的描述 进行分割并赋值
        String[] split = operateType.split(":");
        systemLog.setYl(split[0]);
        systemLog.setOp(split[1]);
        //获取session中的用户
//        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        Subject subject = SecurityUtils.getSubject();
//        EverEmp loginEmp = (EverEmp) subject.getSession().getAttribute("loginEmp");

        //此处为假数据
        EverEmp loginEmp = new EverEmp(); loginEmp.setEid(123L);loginEmp.setEname("王海");

        systemLog.setEid(loginEmp.getEid());
        systemLog.setEname(loginEmp.getEname());
        //获取ip地址
        String ip = Ip.getIpAddress();
        systemLog.setIp(ip);
        Object result = null;
        try {
            result=joinPoint.proceed();
            systemLog.setOp("成功");
        } catch (SQLException e) {
            // 相当于异常通知部分
            systemLog.setOp("失败");// 设置操作结果
        } finally {
            // 相当于最终通知
            systemLog.setDate(new Date(System.currentTimeMillis()));// 设置操作日期
            logMapper.insert(systemLog); // 添加日志记录
        }
        return result ;
    }

}
